<template>
  <div>
    <el-scrollbar :style="{height: bodyHeight+'px'}">
      <el-form ref="formData" :model="formData"  :rules="rules"  label-width="175px"  v-loading="loading" :element-loading-text="loadingText">
        <el-row type="flex" justify="space-around">
          <el-col :span="12">
            <el-form-item label="Default Daily Price"  prop="default_daily_price">
              <el-input placeholder="Please Enter Default Daily Price" class="input-size" v-model="formData.default_daily_price" @change="cacluateAmount">
                <template slot="prepend">{{currency}}</template>
              </el-input>
            </el-form-item>

            <el-form-item label="Guests Included in Price" prop="guests_included">
              <el-input-number  placeholder="Please Enter Guests Included in Price"  class="input-size" v-model="formData.guests_included" :step="1"  :min="0" :max="100" @change="cacluateAmount">
              </el-input-number>
            </el-form-item>

            <el-form-item label="Monthly Price Factor" prop="monthly_price_factor">
              <el-input-number  placeholder="Please Enter Monthly Price Factor"  v-model="formData.monthly_price_factor" :step="0.1" :min="0" :max="1" @change="cacluateAmount">
              </el-input-number>
            </el-form-item>

            <el-form-item label="Weekly Price Factor" prop="weekly_price_factor">
              <el-input-number  placeholder="Please Enter Weekly Price Factore"  v-model="formData.weekly_price_factor" :step="0.1"  :min="0" :max="1" @change="cacluateAmount">
              </el-input-number>
            </el-form-item>

            <el-form-item label="Cleaning Free" prop="cleaning_fee">
              <el-input placeholder="Please Enter Cleaning Free" class="input-size" v-model="formData.cleaning_fee">
                <template slot="prepend">{{currency}}</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Weekend Price" prop="weekend_price">
              <el-input placeholder="Please Enter Weekend Price" class="input-size" v-model="formData.weekend_price">
                <template slot="prepend">{{currency}}</template>
              </el-input>
            </el-form-item>

            <el-form-item label="Price Per Extra Person" prop="price_per_extra_person">
              <el-input placeholder="Please Enter Price Per Extra Person" class="input-size" v-model="formData.price_per_extra_person">
                <template slot="prepend">{{currency}}</template>
              </el-input>
            </el-form-item>

            <el-form-item label="Actual Monthly Price" >
              <el-input placeholder="Please Enter Actual Monthly Price" class="input-size" v-model="actual_monthly_price" disabled>
                <template slot="prepend">{{currency}}</template>
              </el-input>
            </el-form-item>

            <el-form-item label="Actual Weekly Price">
              <el-input placeholder="Please Enter Actual Weekly Price" class="input-size" v-model="actual_weekly_price" disabled>
                <template slot="prepend">{{currency}}</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="doSave">Save Changes</el-button>
          <el-button @click="doClose">Close</el-button>
          <el-button type="danger"  @click="doSynchro">更新定价</el-button>
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </div>
</template>

<script>
    import {addModel,searchModel,get,updateModel,deleteModel} from "@/api/model";
    import {submitAction} from "@/api/task";
    export default {
        name: "EditPricingSettingsForm",
        props:["pid","currency"],
        data() {
            return {
                model: 'PhysicalRoomPricingSetting', //（物理房间列表说明）
                bodyHeight:900,
                parentObj : null, //父对象
                loading:false,
                loadingText:'data load ...',
                actual_monthly_price:0, //Actual Monthly Price
                actual_weekly_price:0,   //Actual Weekly Price
                formData: this.getInitFormData(),
                rules: this.getInitRules()
            }
        },
        created() {
            const _bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;
            // console.log("bodyHeight="+_bodyHeight);
            this.bodyHeight = _bodyHeight - 65;
        },
        mounted(){
            this.loadDatas();
        },
        methods: {
            getInitFormData(){
                return  {
                    id:null,  //null
                    physical_room_hook:null,  //   Hook    PhysicalRoom的外链
                    default_daily_price:0,  // 整数  默认每日单价 最小10USD 最大25000USD
                    weekend_price:0,  //   整数  周末每日单价 最小10USD 最大25000USD
                    guests_included:0,  // 整数  默认价格中包含的入住人数。最小值为1。
                    price_per_extra_person:0,  //  整数  超过包含人数的每人价格。最小5USD 最大300USD
                    monthly_price_factor:0,  //    浮点数 0到1之间。表示折扣幅度，例如0.9表示9折。
                    weekly_price_factor:0,  // 浮点数 0到1之间。表示折扣幅度，例如0.9表示9折。
                    cleaning_fee:0  //    整数  5USD-600USD。清扫费。也可以设置为0，表示不收费
                };
            },
            getInitRules() {
                const custRulesCfg = this.getCustRulesConfig();
                let amountMinMaxCfg = this.transferAmount(10, 25000);
                const guests_amountMinMaxCfg = this.transferAmount(1, 25000);
                const price_per_amountMinMaxCfg = this.transferAmount(5, 300);
                const cleaning_fee_amountMinMaxCfg = this.transferAmount(5, 600);
                const defaultDailyPriceValid = custRulesCfg.floatValid('Default Daily Price',amountMinMaxCfg.minAmount,amountMinMaxCfg.maxAmount);
                const weekendPriceValid = custRulesCfg.floatValid('Weekend Price',amountMinMaxCfg.minAmount,amountMinMaxCfg.maxAmount);
                const guestsIncludedValid = custRulesCfg.intValid('Guests Included in Price',1,100);
                const pricePerValid = custRulesCfg.floatValid('Price Per Extra Person',price_per_amountMinMaxCfg.minAmount,price_per_amountMinMaxCfg.maxAmount);
                const monthly_price_factorValid = custRulesCfg.floatValid('Monthly Price Factor',0,1);
                const weekly_price_factorValid = custRulesCfg.floatValid('Weekly Price Factor',0,1);
                const cleaningFeeValid = custRulesCfg.floatValid('Cleaning Free',cleaning_fee_amountMinMaxCfg.minAmount,cleaning_fee_amountMinMaxCfg.maxAmount);
                return {
                    default_daily_price: [
                        {required: true, validator: defaultDailyPriceValid, trigger: 'blur'}
                    ],
                    weekend_price: [
                        {required: true, validator: weekendPriceValid, trigger: 'blur'}
                    ],
                    guests_included: [
                        {required: true, validator: guestsIncludedValid, trigger: 'blur'}
                    ],
                    price_per_extra_person: [
                        {required: true, validator: pricePerValid, trigger: 'blur'}
                    ],
                    monthly_price_factor: [
                        {required: true, validator: monthly_price_factorValid, trigger: 'blur'}
                    ],
                    weekly_price_factor: [
                        {required: true, validator: weekly_price_factorValid, trigger: 'blur'}
                    ],
                    cleaning_fee: [
                        {required: true, validator: cleaningFeeValid, trigger: 'blur'}
                    ],
                }
            },
            getCustRulesConfig(){
                return {
                    intValid: function(label, min, max){
                        const intValidFun = (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('Please Enter '+label));
                            }
                            try{
                                value = parseInt(value);
                            }catch (e) {
                                callback(new Error(label+' Must be an integer value'));
                            }

                            if (!Number.isInteger(value)) {
                                callback(new Error(label+' Must be an integer value'));
                            }
                            if(min != null && max != null){
                                if(value < min || value > max){
                                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                                }else{
                                    callback();
                                }
                            }
                            if(min != null && max == null){
                                if (min && min > value) {
                                    callback(new Error(label+' Must be greater than or equal to '+min));
                                } else {
                                    callback();
                                }
                            }

                            if(max != null && min == null){
                                if (max && value > max) {
                                    callback(new Error(label+' Must be less than or equal to '+max));
                                } else {
                                    callback();
                                }
                            }
                        };
                        return intValidFun;
                    },
                    floatValid: function(label, min, max,custCb){
                        const intValidFun = (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('Please Enter '+label));
                            }
                            try{
                                console.log(label+" = "+value);
                                value = parseFloat(value);
                            }catch (e) {
                                callback(new Error(label+' Must be an float value'));
                                console.log(label+" = [catch] "+value);
                            }

                            if(min != null && max != null){
                                if(value < min || value > max){
                                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                                }else{
                                    if(custCb){
                                        custCb(rule, value, callback);
                                    }else{
                                        callback();
                                    }
                                }
                            }
                            if(min != null && max == null){
                                if (min && min > value) {
                                    callback(new Error(label+' Must be greater than or equal to '+min));
                                } else {
                                    callback();
                                }
                            }

                            if(max != null && min == null){
                                if (max && value > max) {
                                    callback(new Error(label+' Must be less than or equal to '+max));
                                } else {
                                    callback();
                                }
                            }

                        };
                        return intValidFun;
                    },
                };
            },
            refresh(_parentObj){
                console.log("refresh to do ...");
                this.parentObj = _parentObj;
                this.loadDatas();
            },
            /**
             * 加载数据
             */
            loadDatas(){
                console.log("loadDatas to do ...");
                this.doReset();
                this.loadPricingSettings();
            },
            loadPricingSettings(){
                let _this = this;
                this.loading = true;
                const _pid = this.pid;
                const _parent = _this.parentObj || _this.$parent;
                searchModel(this.model, {
                    search_keys:{physical_room__physical_room_id: _pid}
                }).then(res => {
                    _this.loading = false;
                    if(!res || !res.data){
                        _this.doReset();
                        return;
                    }
                    const list = res.data.list;
                    if(!list  || list.length == 0){
                        _this.doReset();
                        return;
                    }
                   this.formData = list[0];
                    this.cacluateAmount();
                }).catch(reason => {
                    _this.loading = false;
                    console.error(reason);
                });
            },
            /**
             *  不同币种金额转换
             */
            transferAmount($minAmount, $maxAmount){
                let minAmount = 0;
                let maxAmount = 0;
                let standAmount = 0;
                const _currency = this.currency;
                if(_currency == 'USD'){
                    return {minAmount:$minAmount, maxAmount: $maxAmount};
                };
                switch (_currency) {
                    case 'CNY':{ //人民币
                        standAmount = 7.01;
                        break;
                    } case 'JPY':{ //日元
                        standAmount = 109.71;
                        break;
                    } case 'THB':{ //泰铢
                        standAmount = 31.22;
                        break;
                    } case 'HKD':{ //港元
                        standAmount = 7.77;
                        break;
                    } case 'MYR':{ //马来西亚林吉特
                        standAmount = 4.15;
                        break;
                    }
                }
                minAmount = ($minAmount * standAmount).toFixed(2);
                maxAmount = ($maxAmount * standAmount).toFixed(2);
                return {minAmount:minAmount, maxAmount:maxAmount};
            },
            cacluateAmount(){
              const _default_daily_price =  this.formData.default_daily_price || 0;
              const  _monthly_price_factor = this.formData.monthly_price_factor || 0;  //    浮点数 0到1之间。表示折扣幅度，例如0.9表示9折。
              const  _weekly_price_factor = this.formData.weekly_price_factor || 0;;  // 浮点数 0到1之间。表示折扣幅度，例如0.9表示9折。
              this.actual_monthly_price = _default_daily_price * _monthly_price_factor;
              this.actual_weekly_price = _default_daily_price * _weekly_price_factor;
            },
            /**
             *
             * 保存数据
             */
            doSave(){
                console.log("doSave to do ...");
                const _this = this;
                console.log(this.formData);
                this.formData.physical_room_hook = this.pid;
                let _formData = this.formData;
                for(var key in _formData){
                    const val = _formData[key];
                    if(!val && (val !== 0 || val !== '0')){
                        delete _formData[key];
                    }
                }

                this.$refs['formData'].validate((valid) => {
                    if (valid) {
                        _this.loading = true;
                        if(_this.formData.id){
                            updateModel(this.model, _this.formData.id, _formData).then(res => {
                                _this.loading = false;
                                _this.$message({
                                    type: 'info',
                                    message: 'Save Data Success!'
                                });

                            }).catch(reason => {
                                _this.loading = false;
                                console.log("doSave Failure...");
                                console.log(reason);
                                //_this.$message.error('Please Check Input Form Data Has Errors!');
                            });
                        }else{
                            const jsonStr =  JSON.stringify(_formData);
                            addModel(this.model, jsonStr).then(res => {
                                console.log(res);
                                const _id = res.data.id;
                                _this.formData.id = _id;
                                _this.loading = false;
                                _this.$message({
                                    type: 'info',
                                    message: 'Save Data Success!'
                                });

                            }).catch(reason => {
                                _this.loading = false;
                                console.log("doSave Failure...");
                                console.log(reason);
                                // _this.$message.error('Please Check Input Form Data Has Errors!');
                            });
                        }
                    } else {
                        console.log('error submit!!');
                        _this.$message.error('Please Check Input Form Data Has Errors!');
                        return false;
                    }
                });
            },
            doClose(){
              const _parent = this.parentObj ||  this.$parent;
              console.log(_parent);
                _parent.closeDrawer();
            },
            /**
             * 重置表单
             */
            doReset(){
                this.formData = this.getInitFormData();
                if(this.$refs['formData']) this.$refs['formData'].resetFields();
            },
          /**
           * ActionTask ABNB API 同步
           */
          doSynchro(){
            const _this = this;
            const _id = this.formData.id;
            if(!_id){
              _this.$message.error(this.model+' id is null,Please Check Data...!');
              return;
            }

            const actionName = "create_update_pricing_setting";
            this.loadingText = "Calling API: "+actionName+" ...";
            this.loading = true;

            submitAction(this.model, _id,actionName).then(res => {
              this.loading = false;
              _this.$notify({
                title: 'Success',
                message: this.model+' Id:'+ _id +' call API:'+actionName+' succeeded !',
                type: 'success'
              });

            }).catch(reason => {
              _this.loading = false;
              console.log("deleteModel Failure...");
              console.error(reason);
              let errMsg = reason.data || reason.statusText;

              _this.$notify.error({
                title: 'Error',
                message: 'API:'+actionName+'  call error ,Error Reason:['+errMsg+']'
              });
              //_this.$message.error('Please Check Input Form Data Has Errors!');
            });
          }
        }
    }
</script>


<style scoped>
  .input-size{
    width: 85%;
  }
</style>
